/*
 * Copyright (c) 2008, Spagettikod | Stockholm
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *   * Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   * Neither the name of the Spagettikod | Stockholm nor the names of its
 *     contributors may be used to endorse or promote products derived from
 *     this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package com.spagettikod.t437.component;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JViewport;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.spagettikod.t437.T437;
import com.spagettikod.t437.listener.DomainChangeListener;
import com.spagettikod.t437.listener.DomainDoubleClickListener;
import com.spagettikod.t437.simpledb.SimpleDBDomain;

public class SimpleDBJPanel extends JPanel implements DomainChangeListener,
		DomainDoubleClickListener {

	private static final long serialVersionUID = -4968123732645461909L;

	private static final Log log = LogFactory.getLog(SimpleDBJPanel.class);

	private SimpleDBJTable sdbTable;

	// private JPanel domainPanel;

	private JTextArea queryTextArea;

	private JScrollPane tableScrollPane;

	private JComboBox domainCombo;

	private JScrollPane queryAreaScrollPane;

	public SimpleDBJPanel() {
		sdbTable = new SimpleDBJTable();

		createQueryPanel();

		createTableScrollPane();

		setLayout(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();

		c = new GridBagConstraints();
		c.insets = new Insets(8, 8, 8, 8);
		c.gridy = 2;
		c.weightx = 1;
		c.weighty = 0;
		c.fill = GridBagConstraints.HORIZONTAL;
		add(queryAreaScrollPane, c);

		c.insets = new Insets(2, 8, 8, 8);
		c.gridy = 3;
		c.weighty = 1.0;
		c.fill = GridBagConstraints.BOTH;
		add(tableScrollPane, c);

		T437.getApplicationFrame().addComponentListener(new ComponentAdapter() {

			@Override
			public void componentResized(ComponentEvent arg0) {
				if (log.isDebugEnabled()) {
					log.debug("Resized component: " + arg0.getComponent());
				}

				if (sdbTable.getModel() instanceof SimpleDBTableModel) {
					if (log.isDebugEnabled()) {
						log.debug("Table resized, approx. "
								+ sdbTable.getVisibleRows() + " visible rows");
					}
					// Only fetch more rows if there are some present
					if (sdbTable.getRowCount() > 0) {
						sdbTable.executeQuery(queryTextArea.getText());
					}
				}
			}

		});
	}

	/*
	 * Used by tab class to fetch tab name.
	 * 
	 * @see java.awt.Component#getName()
	 */
	@Override
	public String getName() {
		if (domainCombo == null || domainCombo.getItemCount() < 1) {
			return "New Query";
		}
		return getSelectedDomain().toString();
	}

	/**
	 * Create panel with the query text area.
	 */
	private void createQueryPanel() {
		queryTextArea = new JTextArea();

		queryAreaScrollPane = new JScrollPane(queryTextArea);

		queryAreaScrollPane.setMinimumSize(new Dimension(0, 70));
		queryAreaScrollPane.setPreferredSize(new Dimension(0, 70));
	}

	private void createTableScrollPane() {
		tableScrollPane = new JScrollPane(sdbTable);

		tableScrollPane.getVerticalScrollBar().addAdjustmentListener(
				new AdjustmentListener() {

					public void adjustmentValueChanged(AdjustmentEvent e) {
						if (!e.getValueIsAdjusting()) {
							if (log.isDebugEnabled()) {
								log
										.debug("Horizontal scrollbar at "
												+ getHorizontalScrollBarPercent()
												+ "%");
							}
							if (getHorizontalScrollBarPercent() == 100) {
								sdbTable.fetchAllRows(queryTextArea.getText());
							} else if (getHorizontalScrollBarPercent() > 60) {
								sdbTable.executeQuery(queryTextArea.getText());
							}
						}
					}
				});
	}

	/**
	 * Return, in percent, where the horizontal scrollbar is at. Used for lazy
	 * loading (if it's time to load more data).
	 * 
	 * @return
	 */
	private int getHorizontalScrollBarPercent() {
		JViewport vp = tableScrollPane.getViewport();

		Float correctedMaximumHeight = new Float(vp.getViewSize().height)
				- new Float(vp.getViewRect().height);
		Float currentPosition = new Float(vp.getViewRect().y)
				/ correctedMaximumHeight;
		currentPosition = currentPosition * 100;

		return Math.round(currentPosition);
	}

	public void executeQuery() {
		sdbTable.clearTable();
		tableScrollPane.getViewport().setViewPosition(new Point(0, 0));
		sdbTable.executeQuery(queryTextArea.getText());
	}

	private SimpleDBDomain getSelectedDomain() {
		return (SimpleDBDomain) domainCombo.getSelectedItem();
	}

	public void fitColumnWidthsToContent() {
		sdbTable.fitColumnWidthsToContent();
	}

	public void domainChanged(SimpleDBDomain selectedDomain) {
		sdbTable.setDomain(selectedDomain);
		queryTextArea.setText("");
	}

	public void doubleClickedDomain(SimpleDBDomain domain) {
		sdbTable.setDomain(domain);
		executeQuery();
	}
}
